package web.admin.shop.product;

import domain.shop.Product;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackDefaultDataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import web.admin.components.ActionPanel;
import web.admin.components.CheckBoxPanel;
import web.admin.components.SortableProductDataProvider;

import java.util.ArrayList;
import java.util.List;

public class ProductsDataTablePanel extends Panel {
    private AjaxFallbackDefaultDataTable<Product> table;

    public ProductsDataTablePanel(String id, final ProductAdminPanel parent) {
        super(id);
        List<IColumn<Product>> columns = new ArrayList<IColumn<Product>>();
        columns.add(new AbstractColumn<Product>(new Model<String>("Actions")) {
            public void populateItem(Item<ICellPopulator<Product>> cellItem, String componentId,
                                     IModel<Product> model) {
                cellItem.add(new ActionPanel(componentId, model, parent) {
                    @Override
                    public void onClick(AjaxRequestTarget target, IModel model, Panel parent) {
                        ((ProductAdminPanel) parent).replacePanel(((Product) model.getObject()).getId(), target);

                    }
                });
            }


        });

        columns.add(new PropertyColumn<Product>(new Model<String>("ID"), "id", "id"));
        columns.add(new PropertyColumn<Product>(new Model<String>("Name"), "name", "name"));
        columns.add(new PropertyColumn<Product>(new Model<String>("Price"), "price", "price"));
        columns.add(new AbstractColumn<Product>(new Model<String>("Enabled")) {
            public void populateItem(Item<ICellPopulator<Product>> cellItem, String componentId,
                                     IModel<Product> model) {
                cellItem.add(new CheckBoxPanel(componentId, model) {

                    @Override
                    public boolean isChecked(IModel model) {
                        return ((Product) model.getObject()).isEnabled();
                    }
                }
                );
            }
        });
        table = new AjaxFallbackDefaultDataTable<Product>("table", columns,
                new SortableProductDataProvider(), 8);
        add(table);
    }

    public void detachTableModel() {
        table.detachModels();
    }

}
